#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/uinput.h>
#include <unistd.h>
#include "sendkey.h"

#define UINPUT_DEVICE "/dev/input/uinput"
#define UINPUT_NAME "WiiControl keyboard input"

/* Globals */
static int uinp_fd = -1;
struct uinput_user_dev uinp;       // uInput device structure
struct input_event event; // Input device structure

void close_sendkey()
{
  /* Destroy the input device */
  ioctl(uinp_fd, UI_DEV_DESTROY);
  /* Close the UINPUT device */
  close(uinp_fd);
}

int init_sendkey()
{
  // Temporary variable
  int i=0;
  // Open the input device
  uinp_fd = open(UINPUT_DEVICE, O_WRONLY | O_NDELAY);
  if (uinp_fd == 0)
    {
      printf("Unable to open %s\n", UINPUT_DEVICE);
      return -1;
    }
  memset(&uinp,0,sizeof(uinp)); // Intialize the uInput device to NULL
  strncpy(uinp.name, UINPUT_NAME, UINPUT_MAX_NAME_SIZE);
  uinp.id.version = 4;
  uinp.id.bustype = BUS_USB;
  // Setup the uinput device
  ioctl(uinp_fd, UI_SET_EVBIT, EV_KEY);
  ioctl(uinp_fd, UI_SET_EVBIT, EV_REL);
  for (i=0; i < 256; i++) {
    ioctl(uinp_fd, UI_SET_KEYBIT, i);
  }
  /* Create input device into input sub-system */
  write(uinp_fd, &uinp, sizeof(uinp));
  if (ioctl(uinp_fd, UI_DEV_CREATE))
    {
      printf("Unable to create UINPUT device.");
      return -1;
    }
  return 1;
}


void sendkey(int keycode)
{
  // Report BUTTON CLICK - PRESS event
  memset(&event, 0, sizeof(event));
  gettimeofday(&event.time, NULL);
  event.type = EV_KEY;
  event.code = keycode;
  event.value = 1;
  write(uinp_fd, &event, sizeof(event));
  event.type = EV_SYN;
  event.code = SYN_REPORT;
  event.value = 0;
  write(uinp_fd, &event, sizeof(event));
  // Report BUTTON CLICK - RELEASE event
  memset(&event, 0, sizeof(event));
  gettimeofday(&event.time, NULL);
  event.type = EV_KEY;
  event.code = keycode;
  event.value = 0;
  write(uinp_fd, &event, sizeof(event));
  event.type = EV_SYN;
  event.code = SYN_REPORT;
  event.value = 0;
  write(uinp_fd, &event, sizeof(event));
}
